import { createRouter, createWebHistory } from 'vue-router'
// import HomeView from '../views/public/HomeView.vue' // 改为动态导入
// import LoginView from '../views/public/LoginView.vue' // 改为动态导入
// import RegisterView from '../views/public/RegisterView.vue' // 改为动态导入
// import TrendingView from '../views/public/TrendingView.vue' // 改为动态导入
// import VideoDetailView from '../views/public/VideoDetailView.vue' // 改为动态导入
// import ProfileView from '../views/user/ProfileView.vue' // 改为动态导入
// import UploadView from '../views/user/UploadView.vue' // 改为动态导入
// import PostView from '../views/user/PostView.vue' // 改为动态导入
// import SubscriptionsView from '../views/user/SubscriptionsView.vue' // 改为动态导入
// import CategoryView from '../views/public/CategoryView.vue' // 改为动态导入
// import SearchView from '../views/public/SearchView.vue' // 改为动态导入
// import MyVideosView from '../views/user/MyVideosView.vue' // 改为动态导入
// import MyPostsView from '../views/user/MyPostsView.vue' // 改为动态导入
// import SettingsView from '../views/user/SettingsView.vue'  // 改为动态导入
// import CommunityView from '../views/public/CommunityView.vue' // 改为动态导入
// import PostDetailView from '../views/public/PostDetailView.vue' // 改为动态导入

import store from '../store' 
import { nextTick } from 'vue'; // 导入 nextTick

// 定义共享 DefaultLayout 的子路由
const defaultLayoutChildren = [
  {
    path: '',
    name: 'Home',
    component: () => import('../views/public/HomeView.vue')
  },
  {
    path: '/trending',
    name: 'Trending',
    component: () => import('../views/public/TrendingView.vue')
  },
  {
    path: '/community',
    name: 'Community',
    component: () => import('../views/public/CommunityView.vue')
  },
  {
    path: '/post/:id',
    name: 'PostDetail',
    component: () => import('../views/public/PostDetailView.vue'),
    props: true
  },
  {
    path: '/video/:id',
    name: 'VideoDetail',
    component: () => import('../views/public/VideoDetailView.vue'),
    props: true
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('../views/public/SearchView.vue'),
    props: (route) => ({ q: route.query.q })
  },
  {
    path: '/upload',
    name: 'Upload',
    component: () => import('../views/user/UploadView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/post',
    name: 'Post',
    component: () => import('../views/user/PostView.vue'), // 用于创建帖子
    meta: { requiresAuth: true }
  },
  {
    path: '/category/:categoryName',
    name: 'Category',
    component: () => import('../views/public/CategoryView.vue'),
    props: true
  },
  // 添加频道页面路由
  {
    path: '/channel/:userId',
    name: 'Channel',
    component: () => import('../views/public/ChannelView.vue'),
    props: true
  },
  // 用户相关路由
  {
    path: '/user/videos',
    name: 'UserVideos',
    component: () => import('../views/user/MyVideosView.vue'),
    meta: { requiresAuth: true, activeMenu: '/user/videos' }
  },
  {
    path: '/user/posts',
    name: 'UserPosts',
    component: () => import('../views/user/MyPostsView.vue'), // 指向 MyPostsView 组件
    // redirect: { name: 'UserVideos' }, // 移除重定向
    meta: { requiresAuth: true, activeMenu: '/user/posts' }
  },
  {
    path: '/user/subscriptions',
    name: 'UserSubscriptions',
    component: () => import('../views/user/SubscriptionsView.vue'),
    meta: { requiresAuth: true, activeMenu: '/user/subscriptions' }
  },
  {
    path: '/user/settings',
    name: 'UserSettings',
    component: () => import('../views/user/SettingsView.vue'),
    meta: { requiresAuth: true, activeMenu: '/user/settings' }
  }, // 恢复路由定义
  {
    path: '/profile/:userId?',
    name: 'Profile',
    component: () => import('../views/user/ProfileView.vue'),
    meta: { requiresAuth: true, activeMenu: '/profile' } 
  },
  
  
 
]

// 顶层路由
const routes = [
  {
    path: '/',
    component: () => import('@/layouts/DefaultLayout.vue'),
    children: defaultLayoutChildren // 包含所有共享布局的子路由
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/public/LoginView.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/public/RegisterView.vue'),
    meta: { requiresGuest: true }
  },
  // 管理员路由
  {
    path: '/admin',
    name: 'AdminLayout',
    component: () => import('../views/admin/AdminLayout.vue'),
    meta: { requiresAuth: true, requiresAdmin: true },
    children: [
      {
        path: '',
        name: 'AdminDashboard',
        component: () => import('../views/admin/AdminDashboard.vue'),
        meta: { title: '仪表盘' }
      },
      {
        path: 'videos',
        name: 'VideoManagement',
        component: () => import('../views/admin/VideoManagement.vue'),
        meta: { title: '视频管理' }
      },
      {
        path: 'posts',
        name: 'PostManagement',
        component: () => import('../views/admin/PostManagement.vue'),
        meta: { title: '帖子管理' }
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: () => import('../views/admin/UserManagement.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'comments',
        name: 'CommentManagement',
        component: () => import('../views/admin/CommentManagement.vue'),
        meta: { title: '评论管理' }
      },
      {
        path: 'categories',
        name: 'CategoryManagement',
        component: () => import('../views/admin/CategoryManagement.vue'),
        meta: { title: '分类管理' }
      },
      {
        path: 'settings',
        name: 'SettingsManagement', 
        component: () => import('../views/admin/SettingsManagement.vue'),
        meta: { title: '系统设置' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes, // 使用最终构建的 routes
  scrollBehavior(to, from, savedPosition) {
    // ... scroll behavior ...
  }
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const isLoggedIn = store.getters['auth/isAuthenticated'];
  const user = store.state.auth.user; // 获取当前 user 状态

  // 1. 如果已登录但 Vuex 中没有用户信息，先获取用户信息
  if (isLoggedIn && !user) {
    try {
      console.log('路由守卫：用户已登录但信息缺失，尝试获取...');
      await store.dispatch('auth/getProfile');
      console.log('路由守卫：用户信息获取成功，等待 nextTick 后重新导航...');
      // 获取用户信息成功后，等待下一个 DOM 更新周期再重新触发导航
      // 给 Vue 响应式系统一点时间处理状态更新
      nextTick(() => {
        console.log('路由守卫：nextTick 回调，执行 next(to)');
        next(to);
      });
      // 注意：这里不再直接 return next(to)
    } catch (error) {
      // 获取用户信息失败（例如 token 失效），清除登录状态并重定向到登录页
      console.error('路由守卫：获取用户信息失败，清除状态并重定向到登录', error);
      await store.dispatch('auth/logout'); // 确保清除无效的登录状态
      return next({ name: 'Login', query: { redirect: to.fullPath } });
    }
  } else {
    // 如果未登录或用户信息已存在，直接检查权限
    console.log('路由守卫：检查权限...');
    const isAdmin = store.getters['auth/isAdmin'];
    checkPermissions(to, from, next, isLoggedIn, isAdmin);
  }
});

// 辅助函数：检查路由权限 (简化，不再处理 getProfile 后的情况)
function checkPermissions(to, from, next, isLoggedIn, isAdmin) {
  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin && (!isLoggedIn || !isAdmin)) {
    console.warn('路由守卫：需要管理员权限，但用户未登录或不是管理员。重定向到首页。');
    // 可以重定向到无权限页面或首页
    return next({ name: 'Home' });
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth && !isLoggedIn) {
    console.warn('路由守卫：需要登录权限，但用户未登录。重定向到登录页。');
    return next({ name: 'Login', query: { redirect: to.fullPath } });
  }

  // 检查是否是访客页面（登录后不应访问）
  if (to.meta.requiresGuest && isLoggedIn) {
    console.warn('路由守卫：已登录用户访问访客页面。重定向到首页。');
    return next({ name: 'Home' });
  }

  // 所有检查通过
  console.log('路由守卫：权限检查通过。');
  next();
}

export default router